package com.wxx.btc;

import com.wxx.push.IPushListener;
import com.wxx.push.WeChatPush;
import com.wxx.util.CrawlerUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 比特币搬砖，根据火币和ok对btc的定价不同，如果差价大于自定义的阀值，则推送给自己
 */
public class BtcProcess {

    double huoUsdPrice = 0.0;   // 火币交易所比特币的美元价格
    double okUsdPrice = 0.0;    // ok交易所比特币的美元价格
    final double PRICE_NOTIFY_OFFSET = 3.0;   // 两个交易所的差价

    final String URL_HUOBI = "https://www.huobi.io/zh-cn/";         // okex
    final String URL_OKEX = "https://www.okex.com/";                // 火币网

    HashMap<String, String> windowMap = new HashMap<>();

    private static ChromeDriver webDriver;

    static {
        CrawlerUtil.configChromeDriver();
        ChromeOptions option = new ChromeOptions();
        option.addArguments("headless");    // 不打开浏览器窗口，直接在后台执行任务
        webDriver = new ChromeDriver(option);
    }

    private void start() throws InterruptedException {
        webDriver.get(URL_HUOBI);
        windowMap.put(URL_HUOBI, webDriver.getWindowHandle());

        webDriver.switchTo().newWindow(WindowType.TAB);
        webDriver.get(URL_OKEX);
        windowMap.put(URL_OKEX, webDriver.getWindowHandle());

        Thread.sleep(2000);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                parseHuoBi();
                parseOkex();
                calculatePriceOffset();
            }
        }, 0, 10);
    }

    private void parseHuoBi() {
        WebElement element = webDriver.switchTo().window(windowMap.get(URL_HUOBI)).findElement(By.xpath("//dl[@class='btcusdt']")).findElement(By.xpath("//dd[@class='price']"));
        String value = element.getText();
        if (value.contains("≈")) {
            value = value.substring(0, value.indexOf("≈") - 1);
        }
        try {
            huoUsdPrice = Double.parseDouble(value);
        } catch (Exception e) {
            weChatPush("火币价格解析double格式错误");
        }
    }

    private void parseOkex() {
        WebElement element = webDriver.switchTo().window(windowMap.get(URL_OKEX)).findElement(By.xpath("//div[@class='ticker-table-box']")).findElement(By.xpath("//span[@class='legalPrice']"));
        String value = element.getText().replace("$", "").replace("," ,"");
        try {
            okUsdPrice = Double.parseDouble(value);
        } catch (Exception e) {
            weChatPush("okex价格解析double格式错误");
        }
    }

    /**
     * 计算出不同交易所的差价，达到阀值推送
     */
    private void calculatePriceOffset() {
        if (okUsdPrice > 0.0 && huoUsdPrice > 0.0) {
            double offsetPrice = Double.parseDouble(String.format("%.2f", Math.abs(okUsdPrice - huoUsdPrice)));
            System.out.println("当前差价：" + offsetPrice + "    okex:" + okUsdPrice + "    火币:" + huoUsdPrice);
            if (offsetPrice > PRICE_NOTIFY_OFFSET) {
                DecimalFormat df = new DecimalFormat("#.00");
                weChatPush("目前行情：火币价格是" + huoUsdPrice + "      okex的价格是" + okUsdPrice + "，目前差价是" + df.format(offsetPrice) + "，超过了" + PRICE_NOTIFY_OFFSET);
            }
        }
    }

    private long preNotifyTime = 0;
    /**
     * 当出现异常或者达到自己预定的值时，微信推送提醒
     * 【注意】：避免提醒频繁，设置每分钟最多推送一次
     */
    private void weChatPush(String message) {
        if (System.currentTimeMillis() - preNotifyTime >= 60000) {
            WeChatPush.pushText(message, new IPushListener() {
                @Override
                public void onSuccess() {
                    System.out.println("推送到微信成功");
                }

                @Override
                public void onFail(String s) {
                    System.out.println("推送到微信失败：" + s);
                    WeChatPush.pushText(s);
                }
            });
            preNotifyTime = System.currentTimeMillis();
        }
    }

    public static void main(String[] args) {
        try {
            new BtcProcess().start();
            WeChatPush.pushText("比特币差价任务结束");
        } catch (Exception e) {
            System.out.println("错误了");
            WeChatPush.pushText("比特币差价任务出现异常:" + e.getMessage());
            e.printStackTrace();
        }
    }

}